<template>
    <div class="order-apply-invoice">
      <div ref="chartRef" id="bar3Main" style="width: 100%; height: 400px;"></div>
    </div>
</template>
<script lang="ts" setup>
import {onMounted, watch,nextTick,onBeforeUnmount,ref} from 'vue'
import * as echarts from 'echarts'
const emits = defineEmits(['barClick'])
const props = defineProps({
  config: {
    type: Object,
    default: () => {},
  },
  visible: {
    type: Boolean,
    default: false
  }
})

const chartRef = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null
const initChart = ()=> {
    if (!chartRef.value) return

    // 销毁旧实例（避免内存泄漏）
    if (chartInstance) {
        chartInstance.dispose()
        chartInstance = null
    }

    // 创建新实例
    chartInstance = echarts.init(chartRef.value)

      // 添加点击事件监听
    chartInstance.on('click', 'series.bar', (params) => {
      emits('barClick', params)
    })
    updateChart()
}
// 更新图表数据
const updateChart = () => { 
    if (!chartInstance) return
    let option = {
        title: {
            right: '50%',
            top: '0',
            text: props.config.title
        },
        legend: {
          right: '50px',
          top: '20px',
          data: [props.config.legendName]
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: Array.from(props.config.xAxisData)
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {   type: 'bar',
                name: props.config.legendName,
                data: Array.from(props.config.yAxisData),
                label: {
                  show: true, // 显示标签
                  position: 'top',
                  formatter: '{c}个', // 显示数据值
                }
            }
        ]
    };
    chartInstance.setOption(option)
}

watch(() => props.config,(newVal) =>{
     // 如果实例不存在，先初始化
     if (!chartInstance) {
        initChart()
    } else {
        updateChart()
    }
},{deep:true})
// 组件挂载时初始化
onMounted(() => {
  nextTick(() => {
    initChart()
  })
}) 
// 组件卸载时销毁实例（避免内存泄漏）
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

defineExpose({ initChart }) // 暴露方法

</script>
<style lang="scss" scoped></style>